package com.it.myd.help;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class HtmlTagRemoverTypeHandler extends BaseTypeHandler<String> {

    private static final int MAX_LENGTH = 80;

    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // 去除字符串中的 HTML 标签
        if (parameter != null) {
            parameter = parameter.replaceAll("<[^>]*>", "");
            if (parameter.length() > MAX_LENGTH) {
                parameter = parameter.substring(0, MAX_LENGTH) + "...";
            }
        }
        ps.setString(i, parameter);
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        return processString(rs.getString(columnName));
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        return processString(rs.getString(columnIndex));
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return processString(cs.getString(columnIndex));
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return null;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }

    private String processString(String input) {
        // 去除字符串中的 HTML 标签
        if (input != null) {
            input = input.replaceAll("<[^>]*>", "");
            if (input.length() > MAX_LENGTH) {
                input = input.substring(0, MAX_LENGTH) + "...";
            }
        }
        return input;
    }
}